package com.kasax.httpclient.core;

import android.text.TextUtils;

import com.kasax.httpclient.HttpUrl;
import com.kasax.httpclient.beans.Request;
import com.kasax.httpclient.utils.LogUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

import javax.net.ssl.SSLSocketFactory;

public class HttpConnection {
    private static final String HTTPS = "https";
    // 最后一次使用的时间
    public long lastUseTime;
    private Request request;
    private Socket socket;
    private OutputStream outputStream;
    private InputStream inputStream;

    public void setRequest(Request request) {
        this.request = request;
    }

    public Request getRequest() {
        return request;
    }

    // 输入流
    public InputStream call(HttpCondec httpCondec) throws IOException {
        try {
            createSocket();
            httpCondec.writeRequest(outputStream, request);
            return inputStream;
        } catch (IOException e) {
            closeQuietly();
            throw new IOException(e);
        }
    }

    public void closeQuietly() {
        if (null != socket) {
            try {
                socket.close();
            } catch (IOException e) {
                LogUtils.e(getClass(), e);
            }
        }
    }

    private void createSocket() throws IOException {
        if (null == socket || socket.isClosed()) {
            HttpUrl httpUrl = request.url();
            if (httpUrl.getProtocol().equalsIgnoreCase(HTTPS)) {
                // 使用https
                socket = SSLSocketFactory.getDefault().createSocket();
            } else {
                socket = new Socket();
            }
            String host = httpUrl.getHost();
            int port = httpUrl.getPort();
            LogUtils.i(getClass(), "执行连接 host: " + host + " , port: " + port);
            socket.connect(new InetSocketAddress(host, port));
            // 获取服务器的输出流用于向服务器写数据
            outputStream = socket.getOutputStream();
            // 获取服务的输入流，用于获取服务器返回的数据
            inputStream = socket.getInputStream();
        }
    }

    /**
     * 更新最后使用的时间
     */
    public void updateLastUseTime() {
        lastUseTime = System.currentTimeMillis();
    }

    public boolean isSameAddress(String host, int port) {
        if (null == socket) {
            return false;
        }
        return TextUtils.equals(socket.getInetAddress().getHostName(), host) && port == socket.getPort();
    }
}
